package com.yusong.algorithm.search;



import java.util.Arrays;

/**
 * 查找交集
 * 参考MySQL join方案
 */
public class Intersect350 {

    public static void main(String[] args) {
        int[] num1 = {1,2,2,1};
        int[] num2 = {2,2};
        Intersect350 main = new Intersect350();
        main.intersect(num1,num2);
    }

    /**
     * 排序双指针方案
     */
    public int[] intersect(int[] nums1, int[] nums2) {

        Arrays.sort(nums1);
        Arrays.sort(nums2);
        int length1 = nums1.length;
        int length2 = nums2.length;
        int[] result = new int[Math.min(length1, length2)];
        int index1 = 0;
        int index2 = 0;
        int index = 0;
        while (index1 < length1 & index2 < length2){
            int currentValue1 = nums1[index1];
            int currentValue2 = nums2[index2];
            if(currentValue1 == currentValue2){
                result[index++] = currentValue1;
                index1++;
                index2++;
            }else if(currentValue1 < currentValue2){
                index1++;
            }else {
                index2++;
            }

        }

        return Arrays.copyOfRange(result,0, index);
    }

}
